package com.shizhen.aidemo.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;

import org.springframework.ai.chat.client.advisor.SafeGuardAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

@Configuration
public class CommonConfiguration {

//    @Bean
//    public ChatMemory chatMemory() {
//        return new InMemoryChatMemoryRepository();
//    }

//    @Autowired
//    private ChatMemory chatMemory;

    //ChatMemory chatMemory = MessageChatMemoryAdvisor.builder().build();

    //使用chatmemory自带方法实现记忆功能
//    @Bean
//    public ChatClient chatClient(OllamaChatModel model, ChatMemory chatMemory) {
//        return ChatClient
//                .builder(model)
//                .defaultSystem("你是一个下巴仔，你的名字叫龙嘉豪，请以龙嘉豪的身份语气回答问题。")
//                .defaultAdvisors(
//                        new SimpleLoggerAdvisor(),
//                        MessageChatMemoryAdvisor.builder(chatMemory).build()
//                )
//                .build();
//    }

    //使用redis持久化实现聊天记忆功能
    @Bean
    ChatClient chatClient(ChatClient.Builder builder){
        return builder
                .defaultSystem("你是一个智障机器人，你的名字叫龙嘉豪")
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(inMemoryChatMemory()),
                        SafeGuardAdvisor.builder().sensitiveWords(List.of("色情","暴力"))//铭感词
                                .order(2)//设置优先级
                                .failureResponse("抱歉，我无法回答这个问题。").build(),//敏感词处理
                        new SimpleLoggerAdvisor()
                )
                .defaultOptions(ChatOptions.builder()
                        .topP(0.7) //取值越大，生成的随机性越高；取值越低，生成的随机性越低。默认0.8
                        .build())
                .build();
    }

    @Bean
    ChatMemory inMemoryChatMemory() {
        return new InMemoryChatMemory();
    }

    @Bean
    public ChatMemory chatMemory(RedisTemplate<String,Object> redisTemplate) {
        return new ChatRedisMemory(redisTemplate);
    }
}
